//
// Created by ct on 2021/9/23.
//

#include <lib/common.h>
/* 一些宏 */
#define MPORT 43211
#define ADDRESS "127.0.0.1"


# define MESSAGE_SIZE 102400

void send_data(int sockfd) {
    char *query;
    query = malloc(MESSAGE_SIZE + 1);
    for (int i = 0; i < MESSAGE_SIZE; i++) {
        query[i] = 'a';
    }
    query[MESSAGE_SIZE] = '\0';

    const char *cp;
    cp = query;
    size_t remaining = strlen(query);
    while (remaining) {
        int n_written = send(sockfd, cp, remaining, 0);
        fprintf(stdout, "send into buffer %ld \n", n_written);
        if (n_written <= 0) {
            error(1, errno, "send failed");
            return;
        }
        remaining -= n_written;
        cp += n_written;
    }

    return;
}


typedef struct M_SOCKET{
    struct sockaddr_in server_addr;
    int socket_fd;
}p_socket;

p_socket init_p_socket(u_int16_t port, char  * address){
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    inet_pton(AF_INET, address, &server_addr.sin_addr);

    p_socket  ps = {
            .server_addr = server_addr
    };
    return ps;
}
int creat_client(p_socket *mst) {
    int socket_fd;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    socklen_t server_len = sizeof(mst->server_addr);
    int connect_rt = connect(socket_fd, (struct sockaddr *) &mst->server_addr, server_len);
    if (connect_rt < 0) {
        error(1, errno, "connect failed ");
    }
    mst->socket_fd  = socket_fd;
    return socket_fd;
}


int main(int argc,char * argv[]){
    p_socket  ps = init_p_socket(MPORT,ADDRESS);
    p_socket * pps = &ps;

    creat_client(pps);
    printf("start.... \n");

   // make_nonblocking(ps.socket_fd);
    for(;;){
        char input[MAXLINE];
        if (fgets(input, MAXLINE, stdin) != NULL) {
            if (strncmp(input, "shutdown", 8) == 0) {
                write(pps->socket_fd, input, strlen(input));
                shutdown(pps->socket_fd,1);
                return 0;
            }

          //  char *send_lin="Hello!";
            write(pps->socket_fd, input, MAXLINE);
            char recv_line[MAXLINE];
            ssize_t n = read(pps->socket_fd, recv_line, MAXLINE);
            printf("%s \n",recv_line);
      //      close(pps->socket_fd);


        }
    }
}